package com.example.travel.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.travel.common.AjaxResult;
import com.example.travel.common.ValidationEnum;
import com.example.travel.domain.entity.Spot;
import com.example.travel.domain.entity.User;
import com.example.travel.domain.entity.Validation;
import com.example.travel.domain.request.UserPasswordVo;
import com.example.travel.mapper.UserMapper;
import com.example.travel.service.UserService;
import com.example.travel.service.ValidationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;

/**
 * @Author : LinQingLiang
 * @file : UserServiceImpl.java
 * @Since : 2023/1/13 16:29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {


    @Resource
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ValidationService validationService;


    @Override
    public Page page(User user, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum,pageSize);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(user.getAddress() != null && user.getAddress() != "","address",user.getAddress());
        wrapper.eq(user.getEmail() != null && user.getEmail() != "","email",user.getEmail());
        wrapper.like(user.getUsername() != null && user.getUsername() != "","username",user.getUsername());
        return userMapper.page(page,wrapper);
    }

    @Override
    public Page shopUser(Integer id, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum,pageSize);

        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq(id != null ,"t1.id",id);
        return userMapper.shopUser(page,wrapper);
    }

    @Override
    public void deleteByUserSpotId(Integer userSpotId) {
        userMapper.deleteByUserSpotId(userSpotId);
    }

    @Override
    public void updatePassword(UserPasswordVo userPasswordVo) {
        int update = userMapper.updatePassword(userPasswordVo);
        if (update <1 ){
            log.error("密码错误");
        }
    }

    @Override
    public List<Spot> userCollected(Integer userId) {
        return userMapper.userCollected(userId);
    }

    @Override
    public AjaxResult sendEmail(String email,Integer type) throws MessagingException {

        Date now = new Date();

        //先查询相同的类型的email
        QueryWrapper<Validation> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email)
                .eq("type",type)
                //数据库没有过期的code
                .ge("time",now);
        Validation validation = validationService.getOne(wrapper);
        if (validation != null){
            return AjaxResult.error(-1,"当前您的验证码仍然有效，请不要重复发送");
        }



        String code = RandomUtil.randomNumbers(4);

        if (ValidationEnum.LOGIN.getCode().equals(type)){
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);  // 发送人
            message.setTo(email);
            message.setSentDate(now);
            message.setSubject("【程序员林庆良】登录邮箱验证");
            message.setText("您本次登录的验证码是：" + code + "，有效期5分钟。请妥善保管，切勿泄露");
            javaMailSender.send(message);
        }else if(ValidationEnum.FORGET_PASS.getCode().equals(type)){
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message);
            helper.setFrom(from);  // 发送人
            helper.setTo(email);
            helper.setSentDate(now);  // 富文本
            message.setSubject("【程序员林庆良】忘记密码验证");
            String context="<b>尊敬的用户：</b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好，您本次忘记密码的验证码是："+
                    "<b color=\"'red'\">"  + code + "</b><br>"
                    +"，有效期5分钟。请妥善保管，切勿泄露";
            helper.setText(context,true);
            javaMailSender.send(message);
        }

        //发送成功之后将验证码存到数据库
        validationService.saveCode(email,code,type,DateUtil.offsetMinute(now,5));
        return AjaxResult.success();
    }
}
